package it.crudity.web.util;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Wrapper that stores in a {@link ThreadLocal} variable the
 * {@link HttpServletRequest}, the {@link HttpServletResponse} and the
 * {@link ServletContext} used in a request to the servlet container
 * 
 */
public class WebContext {

	private static ThreadLocal<WebContext> tlv = new ThreadLocal<WebContext>();
	private HttpServletRequest request;
	private HttpServletResponse response;
	private ServletContext servletContext;

	protected WebContext(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
		this.request = request;
		this.response = response;
		this.servletContext = servletContext;
	}

	/***
	 * Gets wrapped value
	 * @return WebContext thread local instance
	 */
	public static WebContext getInstance() {
		return tlv.get();
	}

	/***
	 * Associates the request, response and servletContext to the current thread.
	 * @param request 
	 * @param response
	 * @param servletContext
	 */
	public static void create(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
		WebContext wc = new WebContext(request, response, servletContext);
		tlv.set(wc);
	}

	/***
	 * Clears wrapped values.
	 */
	public static void clear() {
		tlv.set(null);
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public ServletContext getServletContext() {
		return servletContext;
	}
}